import { useState } from 'react'
import { AISuggestion } from '../types'
import { Bot, Lightbulb, Clock, AlertTriangle, TrendingUp, Calendar, Scale, Target, Zap, Layers, Loader2, X, Bell, Play, CheckCircle, Flag } from 'lucide-react'

interface AISuggestionCardProps {
  suggestion: AISuggestion
  onAccept: (suggestion: AISuggestion) => void
  onDismiss: (suggestion: AISuggestion) => void
  onAction?: (suggestion: AISuggestion, action: string) => void
}

export default function AISuggestionCard({ suggestion, onAccept, onDismiss, onAction }: AISuggestionCardProps) {
  // 加载状态管理
  const [loadingStates, setLoadingStates] = useState<{ [key: string]: boolean }>({})
  const [showReasoning, setShowReasoning] = useState(false)

  const handleAction = async (action: string) => {
    // 防止重复点击
    if (loadingStates[action]) {
      return
    }

    // 设置加载状态
    setLoadingStates(prev => ({ ...prev, [action]: true }))

    try {
      // 接受/忽略无需走 onAction（避免触发AI参数解析）
      if (action === 'accept') {
        await onAccept(suggestion)
        return
      }
      if (action === 'dismiss') {
        await onDismiss(suggestion)
        return
      }
      // 处理具体的动作
      if (onAction) {
        await onAction(suggestion, action)
      } else {
        // 默认处理
        await onAccept(suggestion)
      }
    } catch (error) {
      console.error('执行动作失败:', error)
    } finally {
      // 清除加载状态
      setLoadingStates(prev => ({ ...prev, [action]: false }))
    }
  }

  const getSuggestionTypeLabel = (type: string) => {
    switch (type) {
      case 'auto_schedule': return '时间安排'
      case 'priority_adjustment': return '优先级调整'
      case 'efficiency_tip': return '效率提升'
      case 'deadline_reminder': return '截止提醒'
      case 'workload_balance': return '工作量平衡'
      case 'habit_optimization': return '习惯优化'
      case 'smart_parse': return '智能解析'
      case 'task_decomposition': return '任务分解'
      default: return type || '一般建议'
    }
  }

  const getSuggestionTypeColor = (type: string) => {
    switch (type) {
      case 'auto_schedule': return 'bg-blue-100 text-blue-700'
      case 'priority_adjustment': return 'bg-orange-100 text-orange-700'
      case 'efficiency_tip': return 'bg-green-100 text-green-700'
      case 'deadline_reminder': return 'bg-red-100 text-red-700'
      case 'workload_balance': return 'bg-purple-100 text-purple-700'
      case 'habit_optimization': return 'bg-indigo-100 text-indigo-700'
      case 'smart_parse': return 'bg-cyan-100 text-cyan-700'
      case 'task_decomposition': return 'bg-pink-100 text-pink-700'
      default: return 'bg-slate-100 text-slate-600'
    }
  }

  const getSuggestionTypeIcon = (type: string) => {
    switch (type) {
      case 'auto_schedule': return Clock
      case 'priority_adjustment': return AlertTriangle
      case 'efficiency_tip': return TrendingUp
      case 'deadline_reminder': return Calendar
      case 'workload_balance': return Scale
      case 'habit_optimization': return Target
      case 'smart_parse': return Zap
      case 'task_decomposition': return Layers
      default: return Lightbulb
    }
  }

  return (
    <div className="bg-white rounded-2xl border border-slate-200 p-5 mb-4 mx-4 hover:shadow-md transition-all duration-200 animate-fade-in-up">
      {/* 头部：来源/标签（移动端换行） + 操作按钮 */}
      <div className="flex items-start justify-between mb-3">
        <div className="flex-1 min-w-0">
          {/* 同行优先：来源 + 类型标签；空间不足时自动换行 */}
          <div className="flex flex-wrap items-center gap-2">
            <div className="w-6 h-6 bg-blue-600 rounded-full flex items-center justify-center">
              <Bot size={12} className="text-white" />
            </div>
            <span className="px-2 py-1 bg-blue-100 text-blue-700 text-xs font-medium rounded-full flex items-center gap-1">
              <Lightbulb size={10} />
              <span>AI建议</span>
            </span>
            {suggestion.type && (() => {
              const IconComponent = getSuggestionTypeIcon(suggestion.type)
              return (
                <span className={`px-2 py-1 text-xs rounded-full flex items-center gap-1 ${getSuggestionTypeColor(suggestion.type)}`}>
                  <IconComponent size={10} />
                  {getSuggestionTypeLabel(suggestion.type)}
                </span>
              )
            })()}
          </div>
        </div>

        <div className="flex gap-2 ml-2">
          {suggestion.actions.map((action, index) => {
            const isLoading = loadingStates[action.action]
            const isAnyLoading = Object.values(loadingStates).some(Boolean)
            
            return (
              <button
                key={index}
                onClick={() => handleAction(action.action)}
                disabled={isLoading || isAnyLoading}
                aria-label={action.label}
                className={`px-3 py-1.5 rounded-lg transition-all duration-200 text-sm font-medium flex items-center gap-2 ${
                  isLoading
                    ? 'bg-slate-300 text-slate-500 cursor-not-allowed'
                    : action.primary
                    ? 'bg-blue-600 hover:bg-blue-700 text-white disabled:bg-blue-400'
                    : 'bg-slate-100 hover:bg-slate-200 text-slate-600 disabled:bg-slate-200 disabled:text-slate-400'
                }`}
                title={isLoading ? '处理中...' : action.label}
              >
                {isLoading ? (
                  <>
                    <Loader2 size={14} className="animate-spin" />
                    <span>处理中</span>
                  </>
                ) : (
                  <>
                    {/* 图标映射 */}
                    {(() => {
                      const map: Record<string, JSX.Element> = {
                        accept: <Bot size={14} />, // 可换成 Check
                        dismiss: <X size={14} />,
                        adjust_date: <Calendar size={14} />,
                        adjust_time: <Clock size={14} />,
                        change_due_date: <Calendar size={14} />,
                        set_reminder: <Bell size={14} />,
                        mark_in_progress: <Play size={14} />,
                        mark_complete: <CheckCircle size={14} />,
                        elevate_priority: <Flag size={14} />,
                        lower_priority: <Flag size={14} />
                      }
                      return map[action.action] || <Bot size={14} />
                    })()}
                    <span className="hidden sm:inline">{action.label}</span>
                  </>
                )}
              </button>
            )
          })}
        </div>
      </div>

      {/* 内容区域 */}
      <div className="mb-4">
        <p className="text-slate-800 text-[13px] leading-relaxed">
          {suggestion.content}
        </p>
        {suggestion.reasoning && (
          <div className="mt-2 p-2 bg-slate-50 rounded-lg">
            <p className="text-xs text-slate-600">
              <span className="font-medium">AI推理:</span> {showReasoning ? suggestion.reasoning : (suggestion.reasoning.length > 90 ? suggestion.reasoning.slice(0, 90) + '…' : suggestion.reasoning)}
            </p>
            {suggestion.reasoning.length > 90 && (
              <button
                onClick={() => setShowReasoning(prev => !prev)}
                className="mt-1 text-xs text-blue-600 hover:text-blue-700"
              >
                {showReasoning ? '收起' : '展开更多'}
              </button>
            )}
          </div>
        )}
      </div>

      {/* 底部：时间信息 + 优先级（统一移到底部） */}
      <div className="flex items-center justify-between text-xs text-slate-500">
        <span>
          {new Date(suggestion.createdAt).toLocaleString('zh-CN', {
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
          })}
        </span>
        {suggestion.priority && (
          <span className={`px-2 py-1 rounded-full text-xs ${
            suggestion.priority === 'high' ? 'bg-red-100 text-red-700' :
            suggestion.priority === 'medium' ? 'bg-yellow-100 text-yellow-700' :
            'bg-green-100 text-green-700'
          }`}>
            {suggestion.priority === 'high' ? '高优先级' :
             suggestion.priority === 'medium' ? '中优先级' : '低优先级'}
          </span>
        )}
      </div>
    </div>
  )
}